﻿package net.wangit.framework.expression;

import net.wangit.Variables;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
/**
 * 变量表达式
 * @author watson
 *
 */
public class VariableExpression {

	private static final String PREFIX = "$V{";
	private static final String SUFFIX = "}";

	public VariableExpression() {
	}

	public static final String resolve(String expression) {
		if (Checker.isEmpty(expression))
			return expression;
		StringBuffer result = new StringBuffer();
		String attribute;
		while ((attribute = StringUtil.find(expression,
				VariableExpression.PREFIX, VariableExpression.SUFFIX)) != null) {
			int index = expression.indexOf((new StringBuilder(
					VariableExpression.PREFIX)).append(attribute).append(
					VariableExpression.SUFFIX).toString());
			result.append(expression.substring(0, index)).append(
					getValue(attribute));
			expression = expression.substring(index + attribute.length()
					+ VariableExpression.PREFIX.length()
					+ VariableExpression.SUFFIX.length());
		}
		result.append(expression);
		return result.toString();
	}

	private static String getValue(String attribute) {
		String attributes[] = attribute.split(",");
		String value = Variables.get(attributes[0]);
		return value != null ? value : attributes.length <= 1 ? ""
				: attributes[1];
	}
}
